package com.df.tv.launcher.model;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import com.df.tv.launcher.entity.RcmdItem;
import com.df.tv.launcher.entity.RcmdSingleCoverData;
import com.df.tv.launcher.fragment.HomeViewPagerFragment;
import com.df.tv.launcher.view.Preview;
import com.df.tv.launcher.view.VideoPlayerView;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.telecom.tv189.comlib.dynamicui.AttributeKey;
import com.telecom.tv189.comlib.dynamicui.Parser;
import com.telecom.tv189.comlib.dynamicui.ViewConfig;
import com.telecom.tv189.comlib.dynamicui.json.ActionPerformer;
import com.telecom.tv189.comlib.dynamicui.json.entity.IntentAction;
import com.telecom.tv189.comlib.dynamicui.view.FrameLayout;
import com.telecom.tv189.comlib.util.Attributes;

/**
 * 首页数据解析器
 * 
 * @author xiao
 * 
 */
public class RecommendDataParser implements Parser {

    public class ParseException extends RuntimeException {
        private static final long serialVersionUID = 7024005915052202614L;

        public ParseException(String string) {
            super(string);
        }
    }

    // 边缘留白（为了放大view）
    public static final int WIDTH_OFFSET = HomeViewPagerFragment.WIDTH_OFFSET;
    public static final int HEIGHT_OFFSET = HomeViewPagerFragment.HEIGHT_OFFSET;

    // 可解析View
    public static final String LAYOUT_PATTERN = FrameLayout.CLASS_PATTERN;
    public static final String IMAGE_PATTERN = Preview.CLASS_PATTERN;
    public static final String VIDEO_PATTERN = VideoPlayerView.CLASS_PATTERN;

    // Image类型View的参数key
    public static final String KEY_IMAGE_IMGURL = Preview.ATTR_IMAGE_SRC;
    public static final String KEY_IMAGE_TITLE = Preview.ATTR_MOVIE_TITLE;
    public static final String KEY_IMAGE_TAG = Preview.ATTR_IMAGE_TAG;

    // Video类型View的参数key
    public static final String KEY_VIDEO_IMGURL = VideoPlayerView.ATTR_COVER_IMG_SRC;
    public static final String KEY_VIDEO_VIDEOURL = VideoPlayerView.ATTR_VIDEO_SRC;
    public static final String KEY_VIDEO_CONTETN_ID = VideoPlayerView.ATTR_VIDEO_CONTETN_ID;

    // 启动数据的参数key
    public static final String KEY_ACTION = ActionPerformer.KEY_ACTION;

    // View类型
    public static final String COVER_VIDEO = "video";
    public static final String COVER_IMAGE = "image";

    @Override
    public ViewConfig parse(String source) {
        return parse(new StringReader(source));
    }

    @Override
    public ViewConfig parse(Reader source) {
        JsonParser parser = new JsonParser();
        try {
            return parse(parser.parse(source).getAsJsonArray());
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public ViewConfig parse(InputStream source) {
        try {
            return parse(new BufferedReader(new InputStreamReader(source, "UTF-8")));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public ViewConfig parse(Object source) {
        JsonArray jsonArray;
        if (source != null && source instanceof JsonArray)
            jsonArray = (JsonArray) source;
        else
            return null;

        ViewConfig root = new ViewConfig(LAYOUT_PATTERN);
        Attributes attrsRoot = new Attributes();
        root.setAttributes(attrsRoot);

        ViewConfig config;
        Attributes attrs;
        ActionPerformer performer;
        RcmdItem item;
        RcmdSingleCoverData data;
        Gson gson = new Gson();
        try {
            for (JsonElement jsonElement : jsonArray) {
                item = gson.fromJson(jsonElement, RcmdItem.class);
                attrs = new Attributes();
                config = new ViewConfig();
                config.setAttributes(attrs);
                // attributes for layout
                attrs.add(AttributeKey.LAYOUT_MARGIN_TOP, item.getTop() + HEIGHT_OFFSET);
                attrs.add(AttributeKey.LAYOUT_MARGIN_LEFT, item.getLeft() + WIDTH_OFFSET);
                attrs.add(AttributeKey.LAYOUT_WIDTH, item.getWidth());
                attrs.add(AttributeKey.LAYOUT_HEIGHT, item.getHeight());
                attrs.add(AttributeKey.FOCUS, item.isFocus());

                // current Page should be show
                if (item.isFocus())
                    attrsRoot.add(AttributeKey.FOCUS, item.isFocus());

                if (RcmdSingleCoverData.DATA_TYPE.equals(item.getDataType())) {
                    data = gson.fromJson(item.getData(), RcmdSingleCoverData.class);
                    if (COVER_IMAGE.equals(data.getType())) {
                        config.setClassPattern(IMAGE_PATTERN);
                        attrs.add(KEY_IMAGE_IMGURL, data.getImage());
                        attrs.add(KEY_IMAGE_TITLE, getDecodedStr(data.getTitle()));
                        attrs.add(KEY_IMAGE_TAG, getDecodedStr(data.getTag()));
                    }
                    else if (COVER_VIDEO.equals(data.getType())) {
                        config.setClassPattern(VIDEO_PATTERN);
                        attrs.add(KEY_VIDEO_IMGURL, data.getImage());
                        attrs.add(KEY_VIDEO_VIDEOURL, data.getVideo());
                        attrs.add(KEY_VIDEO_CONTETN_ID, data.getVideoid());
                    }
                    else
                        throw new ParseException("unsupport cover type:" + data.getType());
                    if (IntentAction.ACTION_TYPE.equals(data.getActionType())) {
                        performer = new LauncherActionPerformer();
                        performer.setArguments(data.getAction());
                        attrs.add(KEY_ACTION, performer);
                    }
                }
                root.addChild(config);
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return root;
    }

    private String getDecodedStr(String str) {
        try {
            return URLDecoder.decode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        } catch (NullPointerException e) {
            e.printStackTrace();
            return null;
        }
    }
}
